import { DictTag } from "@/components/common/DictTag";
import { addDialog } from "@/components/ReDialog";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { hasAuth, useRouterNavigation } from "@/router/utils";
import { dealDataExcept, dealDataRide, ExportDownload } from "@/utils/common";
import { message } from "@/utils/message";
import { handleTree } from "@/utils/tree";
import type { PaginationProps } from "@pureadmin/table";
import { cloneDeep, createFormData, deviceDetection } from "@pureadmin/utils";
import { ElLoading, ElMessageBox } from "element-plus";
import { h, nextTick, onMounted, reactive, type Ref, ref, toRaw } from "vue";
import { usePublicHooks } from "../../hooks";
import importForm from "../form/import.vue";
import imWarningForm from "../form/imWarning.vue";
import editForm from "../form/index.vue";
import type { FormItemProps } from "../utils/types";

import { getBrandPage } from "@/api/basicArchives/brand";
import { getAreaPage } from "@/api/basicArchives/regiona";

import {
  exportStore,
  getStorePage,
  importStore,
  importWarning,
  storeAdd,
  storeChangeStatus,
  storeDelete,
  storeUpdate
} from "@/api/basicArchives/storeManagement";

export function useStore(treeRef?: Ref) {
  const form = reactive({
    storeName: undefined,
    storeCode: undefined,
    status: undefined,
    type: "",
    brandId: undefined,
    areaId: undefined
  });

  const loading = ref(false);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 100]
  });

  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();

  const columns: TableColumnList = [
    {
      label: "门店编码",
      prop: "storeCode",
      minWidth: 150
    },
    {
      label: "门店名称",
      prop: "storeName",
      minWidth: 160
    },
    {
      label: "经营属性",
      prop: "type",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <>
          <DictTag dict-type="BUSINES_ATR" dict-value={row.type} />
        </>
      )
    },
    {
      label: "所属品牌",
      prop: "brandName",
      minWidth: 120
    },
    {
      label: "门店状态",
      prop: "status",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={0}
          inactive-value={1}
          active-text="营业"
          inactive-text="撤铺"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "门店标签",
      prop: "labelList",
      minWidth: 120,
      cellRenderer: ({ row }) => (
        <>
          {row.labelList.map(i => (
            <el-tag
              style={{ marginRight: "5px" }}
              type="primary"
              effect="plain"
            >
              {i.labelName}
            </el-tag>
          ))}
        </>
      )
    },
    {
      label: "所属区域",
      prop: "areaName",
      minWidth: 120
    },
    {
      label: "门店地址",
      prop: "address",
      minWidth: 200,
      showOverflowTooltip: true,
      hide: true
    },
    {
      label: "门店联系人",
      prop: "contacts",
      width: 150,
      hide: true
    },
    {
      label: "联系方式",
      prop: "contact",
      width: 150,
      hide: true
    },
    {
      label: "小娃娃均价",
      prop: "avgPrice",
      width: 100,
      cellRenderer: ({ row }) => (
        <>
          <div>
            {dealDataExcept(row.avgPrice) == 0
              ? undefined
              : dealDataExcept(row.avgPrice)}
          </div>
        </>
      ),
      hide: true
    },
    {
      label: "备注",
      prop: "des",
      minWidth: 150,
      showOverflowTooltip: true,
      hide: true
    },
    {
      label: "抓机商品预警上限",
      minWidth: 140,
      hide: true,
      cellRenderer: ({ row }) => (
        <>
          <div>{row.storeWarningTopList[0]?.captureGoodsPrice}</div>
        </>
      )
    },
    {
      label: "兑换礼品预警上限",
      minWidth: 140,
      hide: true,
      cellRenderer: ({ row }) => (
        <>
          <div>{row.storeWarningTopList[0]?.exchangeGiftPrice}</div>
        </>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 1 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.storeName
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          storeChangeStatus({
            id: row.id,
            status: row.status
          }).then(res => {
            if (res.code == 200) {
              message(
                `已${row.status === 1 ? "停用" : "启用"}${row.storeName}`,
                {
                  type: "success"
                }
              );
            }
          });
        }, 300);
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const params = {
      ...toRaw(form),
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    const { data } = await getStorePage(params);
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const formRef = ref();

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}门店`,
      props: {
        formInline: {
          id: row?.id ?? "",
          storeName: row?.storeName ?? "",
          wtCode: row?.wtCode ?? undefined,
          contacts: row?.contacts ?? "",
          address: row?.address ?? "",
          contact: row?.contact ?? "",
          type: row?.type ?? "",
          brandId: row?.brandId ?? "",
          areaId: row?.areaId ?? "",
          labelIdList: row?.labelIdList ?? [],
          depositoryIdList: row?.depositoryIdList ?? [],
          avgPrice:
            dealDataExcept(row?.avgPrice) == 0
              ? undefined
              : dealDataExcept(row?.avgPrice),
          des: row?.des ?? ""
        }
      },
      width: "600px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = cloneDeep(options.props.formInline as FormItemProps);

        // 小娃娃均价放大10倍
        curData.avgPrice =
          dealDataRide(curData.avgPrice) == 0
            ? undefined
            : dealDataRide(curData.avgPrice);
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          setTimeout(() => done(), 800); // 关闭弹窗
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            // console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              const { code } = await storeAdd(curData);
              if (code == 200) {
                chores();
              }
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              const { code } = await storeUpdate(curData);
              if (code == 200) {
                chores();
              }
            }
          }
          closeLoading();
        });
      }
    });
  }

  async function handleDelete(row) {
    const res = await storeDelete(row.id);
    if (res.code != 200) return;
    message(`删除成功`, { type: "success" });
    onSearch();
  }

  const { push } = useRouterNavigation();
  function openDetil(row?: FormItemProps) {
    push(
      {
        path: `/basicArchives/storeManagement/detail`,
        // name: "StoreManagementDetail",
        query: { id: row.id }
      },
      () => {
        // 成功后的操作
        console.log("成功后的操作");
      },
      () => {
        // 失败后的操作
        console.log("失败后的操作");
      }
    );
  }

  let options2 = ref([]);
  const params = {
    pageNum: 1,
    pageSize: 999
  };
  async function brandList() {
    const { data } = await getBrandPage(params);
    options2.value = data.records;
  }

  const treeLoading = ref(true);
  const treeData = ref([]);
  function onTreeSelect(treeData) {
    let { id, selected } = treeData;
    form.areaId = selected && id != 0 ? id : undefined;
    onSearch();
  }

  /** 加载全国门店菜单tree */
  const loadTree = async () => {
    treeLoading.value = true;
    // 获取菜单
    let params = {
      pageNum: 1,
      pageSize: 999
    };
    const { data } = await getAreaPage(params);

    data.records.forEach(item => {
      item.parentId = 0;
    });

    data.records.unshift({
      id: 0,
      areaName: "全国门店"
    });
    treeData.value = handleTree(data.records || []);
    // 默认选择第一个
    treeLoading.value = false;
    nextTick(() => {
      let tempData = treeData.value[0];
      treeRef && treeRef.value.setCurrentKey(tempData.id);
    });
  };

  function handleSizeChange(val: number) {
    // console.log(`${val} items per page`);
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    // console.log(`current page: ${val}`);
    pagination.currentPage = val;
    onSearch();
  }

  // 批量导入
  let loadinglock;
  const importRef = ref();
  function batchImport(title = "批量导入门店", row?: any) {
    addDialog({
      title,
      props: {
        formInline: {
          fileList: row?.fileList ?? undefined
        }
      },
      width: "500px",
      sureBtnLoading: true,
      fullscreenIcon: true,
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => h(importForm, { ref: importRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = importRef.value.getRef();
        const curData = options.props.formInline as any;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          setTimeout(() => done(), 800); // 关闭弹窗
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            loadinglock = ElLoading.service({
              lock: true,
              text: "正在上传文件，请稍候...",
              background: "rgba(0, 0, 0, 0.7)"
            });
            // console.log("curData", curData);
            // 表单规则校验通过
            // 实际开发先调用新增接口，再进行下面操作
            const formData = createFormData({
              files: curData.fileList.map(file => ({ raw: file.raw })) // file 文件
            });

            importStore(formData)
              .then(() => {
                chores();
              })
              .catch(e => {
                let tips = e || "导入异常";
                if (e && e.split(";").length > 0) {
                  tips = e.split(";").join("<br />");
                }
                ElMessageBox.alert(tips, "温馨提示", {
                  dangerouslyUseHTMLString: true,
                  showClose: true,
                  confirmButtonText: "确认"
                });
              });
          }
          if (loadinglock) loadinglock.close();
          closeLoading();
        });
      }
    });
  }

  // 批量导入预警金额
  const importWarnRef = ref();
  function exportExcel(title = "批量导入预警金额", row?: any) {
    addDialog({
      title,
      props: {
        formInline: {
          fileList: row?.fileList ?? undefined
        }
      },
      width: "500px",
      sureBtnLoading: true,
      fullscreenIcon: true,
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => h(imWarningForm, { ref: importWarnRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = importWarnRef.value.getRef();
        const curData = options.props.formInline as any;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          setTimeout(() => done(), 800); // 关闭弹窗
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            loadinglock = ElLoading.service({
              lock: true,
              text: "正在上传文件，请稍候...",
              background: "rgba(0, 0, 0, 0.7)"
            });
            // console.log("curData", curData);
            // 表单规则校验通过
            // 实际开发先调用新增接口，再进行下面操作
            const formData = createFormData({
              files: curData.fileList.map(file => ({ raw: file.raw })) // file 文件
            });

            importWarning(formData)
              .then(() => {
                chores();
              })
              .catch(e => {
                let tips = e || "导入异常";
                if (e && e.split(";").length > 0) {
                  tips = e.split(";").join("<br />");
                }
                ElMessageBox.alert(tips, "温馨提示", {
                  dangerouslyUseHTMLString: true,
                  showClose: true,
                  confirmButtonText: "确认"
                });
              });
          }
          if (loadinglock) loadinglock.close();
          closeLoading();
        });
      }
    });
  }

  onMounted(async () => {
    onSearch();
    brandList();

    await loadTree();
    treeLoading.value = false;
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    useRenderIcon,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    openDialog,
    handleDelete,
    openDetil,
    exportExcel,
    hasAuth,
    options2,
    deviceDetection,
    treeData,
    treeLoading,
    onTreeSelect,
    loadTree,
    handleSizeChange,
    handleCurrentChange,
    batchImport,
    ExportDownload,
    exportStore
  };
}
